import 'package:aitao_flutter/common_ui/back_nav.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../../common_ui/circle_avatar.dart';
import '../../common_ui/empty_view.dart';
import '../../model/black_list_model.dart';
import '../../refresh/custom_refresh_footer.dart';
import '../../refresh/custom_refresh_header.dart';
import '../../request/api.dart';
import '../../request/requestManager.dart';
import '../../style/box_style.dart';
import '../../style/color_style.dart';
import '../../style/edgeInsets_style.dart';
import '../../style/radius_style.dart';
import '../../style/text_style.dart';
import '../../utils/common_utils.dart';

class BlackListPage extends StatefulWidget {
  const BlackListPage({super.key});

  @override
  State<BlackListPage> createState() => _BlackListPageState();
}

class _BlackListPageState extends State<BlackListPage> {
  int _page = 1;
  int _totalPage = 1;
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  List<BlackListModel> _list = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: BackNavigation(
          title: '黑名单',
        ),
        body: _list.isEmpty
            ? EmptyView()
            : SmartRefresher(
                controller: _refreshController,
                enablePullDown: true,
                enablePullUp: _page < _totalPage,
                onRefresh: _onRefresh,
                onLoading: _onLoading,
                header: CustomClassicHeader(),
                footer: const CustomClassicFooter(),
                child: ListView.builder(
                  itemBuilder: ((context, index) {
                    return _userItem(index);
                  }),
                  itemCount: _list.length,
                ),
              ));
  }

  Widget _userItem(int index) {
    BlackListModel model = _list[index];
    return GestureDetector(
      child: Container(
        color: ColorStyle.whiteColor,
        padding: EdgeInsetsStyle.edgeInsets(16, 20),
        child: Row(children: [
          CircleAvatarWidget(
              url: model.avatar ?? '', gender: model.gender ?? 1),
          Box.hBox12,
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Text(
                    model.nickname ?? '',
                    style: Styles.normalText_15,
                  ),
                  Box.hBox3,
                  Visibility(
                      visible: model.vip != 2 ? true : false,
                      child: Image.asset(CommonUtils.setVipImagePath(
                          model.vip ?? 2, model.vipLevel ?? 0)))
                ],
              ),
              Box.vBox(8),
              Text(
                model.createTime ?? '',
                style: const TextStyle(
                    fontSize: 12, color: ColorStyle.aaaaaaColor),
              )
            ],
          ),
          const Spacer(),
          GestureDetector(
            child: _rightBtnWidget(model.isBlack == 1 ? '取消拉黑' : '拉黑'),
            onTap: () {
              cancelBlack(model.userid ?? 0, index);
            },
          )
        ]),
      ),
      onTap: () {
        // Get.toNamed(Routes.personalPage, parameters: {'userId': model.userid.toString()});
      },
    );
  }

  Widget _rightBtnWidget(String title) {
    return Container(
      padding: EdgeInsetsStyle.edgeInsets(15, 6),
      alignment: Alignment.center,
      decoration: BoxDecoration(
          borderRadius: RadiusStyle.radiusAll(6),
          gradient: ColorStyle.gravitationItemColor),
      child: Text(
        title,
        style: Styles.whiteText_11,
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    loadNewList();
  }

  void cancelBlack(int userId, int index) async {
    if (userId == 0) return;
    var result = await RequestManager()
        .post(API.blackOperation, params: {'black_uid': userId});
    if (result != null && result['code'] == 0) {
      setState(() {
        _list[index].isBlack = _list[index].isBlack == 1 ? 0 : 1;
      });
    }
  }

  void loadNewList() async {
    var result =
        await RequestManager().post(API.blackList, params: {'page': _page});
    if (result != null && result['code'] == 0) {
      _list.clear();
      _page = result['data']['page'];
      _totalPage = result['data']['total_page'];
      List tempList = result['data']['list'];
      _list = tempList.map((e) {
        return BlackListModel.fromJson(e);
      }).toList();
      if (_page >= _totalPage) {
        _refreshController.loadNoData();
      }
      if (mounted) {
        setState(() {});
      }
    }
  }

  void loadMoreList() async {
    var result = await RequestManager()
        .post(API.blackList, params: {'type': 0, 'page': _page});
    if (result != null && result['code'] == 0) {
      _page = result['data']['page'];
      _totalPage = result['data']['total_page'];
      if (_page >= _totalPage) {
        _refreshController.loadNoData();
      }
      List tempList = result['data']['list'];
      _list.addAll(tempList.map((e) {
        BlackListModel m = BlackListModel.fromJson(e);
        return m;
      }));
      if (mounted) {
        setState(() {});
      }
    }
  }

  void _onRefresh() {
    _page = 1;
    _totalPage = 1;
    loadNewList();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    _page += 1;
    loadMoreList();
    _refreshController.loadComplete();
  }
}
